<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring源码系列-第7章-AOP的执行流程原理和监听器原理 | 风祈的时光录</title><meta name="keywords" content="Spring，框架，spring源码"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="AOP执行流程和监听器原理">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring源码系列-第7章-AOP的执行流程原理和监听器原理">
<meta property="og:url" content="https://imlql.cn/post/fb3552e0.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="AOP执行流程和监听器原理">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2022-04-17T04:01:02.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.033Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/fb3552e0"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring源码系列-第7章-AOP的执行流程原理和监听器原理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-04-17T04:01:02.000Z" title="发表于 2022-04-17 12:01:02">2022-04-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.033Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E6%BA%90%E7%A0%81V1/">源码V1</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第7章-AOP的执行流程原理和监听器原理"><a href="#第7章-AOP的执行流程原理和监听器原理" class="headerlink" title="第7章-AOP的执行流程原理和监听器原理"></a>第7章-AOP的执行流程原理和监听器原理</h1><h2 id="流程图-AOP运行流程原理"><a href="#流程图-AOP运行流程原理" class="headerlink" title="流程图-AOP运行流程原理"></a>流程图-AOP运行流程原理</h2><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.7/spring-sourcecode-v1/flow_chart/AOP%E8%BF%90%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%8E%9F%E7%90%86.jpg">

<h2 id="由Aop的执行流程引出方法拦截器"><a href="#由Aop的执行流程引出方法拦截器" class="headerlink" title="由Aop的执行流程引出方法拦截器"></a>由Aop的执行流程引出方法拦截器</h2><h3 id="创建完代理对象之后，怎么执行的呢？"><a href="#创建完代理对象之后，怎么执行的呢？" class="headerlink" title="创建完代理对象之后，怎么执行的呢？"></a>创建完代理对象之后，怎么执行的呢？</h3><p>断点打到这里，F7进入方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012195045643.png"/>

<p>自然而然的跳到了cglib这里</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012195313364.png"  />

<h4 id="CglibAopProxy-intercept"><a href="#CglibAopProxy-intercept" class="headerlink" title="CglibAopProxy#intercept()"></a>CglibAopProxy#intercept()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object proxy, Method method, Object[] args, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   Object oldProxy = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">boolean</span> setProxyContext = <span class="keyword">false</span>;</span><br><span class="line">   Object target = <span class="keyword">null</span>;</span><br><span class="line">   TargetSource targetSource = <span class="keyword">this</span>.advised.getTargetSource();</span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.advised.exposeProxy) &#123;</span><br><span class="line">         <span class="comment">// Make invocation available if necessary.</span></span><br><span class="line">         oldProxy = AopContext.setCurrentProxy(proxy);</span><br><span class="line">         setProxyContext = <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// Get as late as possible to minimize the time we &quot;own&quot; the target, in case it comes from a pool...</span></span><br><span class="line">      target = targetSource.getTarget();</span><br><span class="line">      Class&lt;?&gt; targetClass = (target != <span class="keyword">null</span> ? target.getClass() : <span class="keyword">null</span>);</span><br><span class="line">      List&lt;Object&gt; chain = <span class="keyword">this</span>.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);</span><br><span class="line">      Object retVal;</span><br><span class="line">      <span class="comment">// Check whether we only have one InvokerInterceptor: that is,</span></span><br><span class="line">      <span class="comment">// no real advice, but just reflective invocation of the target.</span></span><br><span class="line">      <span class="keyword">if</span> (chain.isEmpty() &amp;&amp; Modifier.isPublic(method.getModifiers())) &#123;</span><br><span class="line">         Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);</span><br><span class="line">         retVal = methodProxy.invoke(target, argsToUse);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// We need to create a method invocation...</span></span><br><span class="line">         retVal = <span class="keyword">new</span> CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();</span><br><span class="line">      &#125;</span><br><span class="line">      retVal = processReturnType(proxy, target, method, retVal);</span><br><span class="line">      <span class="keyword">return</span> retVal;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (target != <span class="keyword">null</span> &amp;&amp; !targetSource.isStatic()) &#123;</span><br><span class="line">         targetSource.releaseTarget(target);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (setProxyContext) &#123;</span><br><span class="line">         <span class="comment">// Restore old proxy.</span></span><br><span class="line">         AopContext.setCurrentProxy(oldProxy);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="CglibAopProxy-getInterceptorsAndDynamicInterceptionAdvice"><a href="#CglibAopProxy-getInterceptorsAndDynamicInterceptionAdvice" class="headerlink" title="CglibAopProxy#getInterceptorsAndDynamicInterceptionAdvice()"></a>CglibAopProxy#getInterceptorsAndDynamicInterceptionAdvice()</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012195459849.png"  />

<ol>
<li>把5个增强器变成了方法拦截器，增强器只是保存信息的，真正执行还得靠方法拦截器。</li>
<li>我们再给上面的470行打上断点，看下之前是如何生成方法拦截器的。因为第一次生成的时候没有缓存，肯定能进去470行。</li>
</ol>
<h3 id="如何生成的方法拦截器？"><a href="#如何生成的方法拦截器？" class="headerlink" title="如何生成的方法拦截器？"></a>如何生成的方法拦截器？</h3><h4 id="Debug调用栈"><a href="#Debug调用栈" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012201950845.png"  />

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012202049726.png"  />

<p>可以看到就是在之前创建代理对象的时候增强器转成的拦截器</p>
<h4 id="DefaultAdvisorChainFactory-getInterceptorsAndDynamicInterceptionAdvice-开始将增强器转为方法拦截器"><a href="#DefaultAdvisorChainFactory-getInterceptorsAndDynamicInterceptionAdvice-开始将增强器转为方法拦截器" class="headerlink" title="DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice()开始将增强器转为方法拦截器"></a>DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice()开始将增强器转为方法拦截器</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Object&gt; <span class="title">getInterceptorsAndDynamicInterceptionAdvice</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      Advised config, Method method, <span class="meta">@Nullable</span> Class&lt;?&gt; targetClass)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// This is somewhat tricky... We have to process introductions first,</span></span><br><span class="line">   <span class="comment">// but we need to preserve order in the ultimate list.</span></span><br><span class="line">   AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();</span><br><span class="line">   Advisor[] advisors = config.getAdvisors();</span><br><span class="line">   List&lt;Object&gt; interceptorList = <span class="keyword">new</span> ArrayList&lt;&gt;(advisors.length);</span><br><span class="line">   Class&lt;?&gt; actualClass = (targetClass != <span class="keyword">null</span> ? targetClass : method.getDeclaringClass());</span><br><span class="line">   Boolean hasIntroductions = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">for</span> (Advisor advisor : advisors) &#123;</span><br><span class="line">      <span class="keyword">if</span> (advisor <span class="keyword">instanceof</span> PointcutAdvisor) &#123;</span><br><span class="line">         <span class="comment">// Add it conditionally.</span></span><br><span class="line">         PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;</span><br><span class="line">         <span class="keyword">if</span> (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) &#123;</span><br><span class="line">            MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();</span><br><span class="line">            <span class="keyword">boolean</span> match;</span><br><span class="line">            <span class="keyword">if</span> (mm <span class="keyword">instanceof</span> IntroductionAwareMethodMatcher) &#123;</span><br><span class="line">               <span class="keyword">if</span> (hasIntroductions == <span class="keyword">null</span>) &#123;</span><br><span class="line">                  hasIntroductions = hasMatchingIntroductions(advisors, actualClass);</span><br><span class="line">               &#125;</span><br><span class="line">               match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">               match = mm.matches(method, actualClass);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (match) &#123;</span><br><span class="line">               MethodInterceptor[] interceptors = registry.getInterceptors(advisor);<span class="comment">//（如果是通知方法）把增强器转拦截器</span></span><br><span class="line">               <span class="keyword">if</span> (mm.isRuntime()) &#123;</span><br><span class="line">                  <span class="comment">// Creating a new object instance in the getInterceptors() method</span></span><br><span class="line">                  <span class="comment">// isn&#x27;t a problem as we normally cache created chains.</span></span><br><span class="line">                  <span class="keyword">for</span> (MethodInterceptor interceptor : interceptors) &#123;</span><br><span class="line">                     interceptorList.add(<span class="keyword">new</span> InterceptorAndDynamicMethodMatcher(interceptor, mm));</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="keyword">else</span> &#123;</span><br><span class="line">                  interceptorList.addAll(Arrays.asList(interceptors));</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (advisor <span class="keyword">instanceof</span> IntroductionAdvisor) &#123;</span><br><span class="line">         IntroductionAdvisor ia = (IntroductionAdvisor) advisor;</span><br><span class="line">         <span class="keyword">if</span> (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) &#123;</span><br><span class="line">            Interceptor[] interceptors = registry.getInterceptors(advisor);</span><br><span class="line">            interceptorList.addAll(Arrays.asList(interceptors));</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         Interceptor[] interceptors = registry.getInterceptors(advisor);</span><br><span class="line">         interceptorList.addAll(Arrays.asList(interceptors));</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> interceptorList; <span class="comment">//所有增强器转好拦截器</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="DefaultAdvisorAdapterRegistry-getInterceptors"><a href="#DefaultAdvisorAdapterRegistry-getInterceptors" class="headerlink" title="DefaultAdvisorAdapterRegistry#getInterceptors()"></a>DefaultAdvisorAdapterRegistry#getInterceptors()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> List&lt;AdvisorAdapter&gt; adapters = <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">3</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> MethodInterceptor[] getInterceptors(Advisor advisor) <span class="keyword">throws</span> UnknownAdviceTypeException &#123;</span><br><span class="line">      List&lt;MethodInterceptor&gt; interceptors = <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">3</span>);</span><br><span class="line">      Advice advice = advisor.getAdvice();</span><br><span class="line">      <span class="keyword">if</span> (advice <span class="keyword">instanceof</span> MethodInterceptor) &#123;</span><br><span class="line">         interceptors.add((MethodInterceptor) advice);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">for</span> (AdvisorAdapter adapter : <span class="keyword">this</span>.adapters) &#123;</span><br><span class="line">         <span class="keyword">if</span> (adapter.supportsAdvice(advice)) &#123; <span class="comment">//这里应该是一个适配器模式</span></span><br><span class="line">            interceptors.add(adapter.getInterceptor(advisor)); </span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (interceptors.isEmpty()) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> UnknownAdviceTypeException(advisor.getAdvice());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> interceptors.toArray(<span class="keyword">new</span> MethodInterceptor[<span class="number">0</span>]);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>增强器只是保存了哪些方法是通知方法的详细信息</li>
<li>拦截器里写了反射执行通知方法的逻辑，具体执行还得要方法拦截器</li>
</ol>
<h4 id="MethodBeforeAdviceAdapter适配器模式将增强器适配成方法拦截器"><a href="#MethodBeforeAdviceAdapter适配器模式将增强器适配成方法拦截器" class="headerlink" title="MethodBeforeAdviceAdapter适配器模式将增强器适配成方法拦截器"></a>MethodBeforeAdviceAdapter适配器模式将增强器适配成方法拦截器</h4><p>适配器模式适配一下</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MethodBeforeAdviceAdapter</span> <span class="keyword">implements</span> <span class="title">AdvisorAdapter</span>, <span class="title">Serializable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsAdvice</span><span class="params">(Advice advice)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> (advice <span class="keyword">instanceof</span> MethodBeforeAdvice);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> MethodInterceptor <span class="title">getInterceptor</span><span class="params">(Advisor advisor)</span> </span>&#123;</span><br><span class="line">      MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> MethodBeforeAdviceInterceptor(advice);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="MethodBeforeAdviceInterceptor"><a href="#MethodBeforeAdviceInterceptor" class="headerlink" title="MethodBeforeAdviceInterceptor"></a>MethodBeforeAdviceInterceptor</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodBeforeAdviceInterceptor</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span>, <span class="title">BeforeAdvice</span>, <span class="title">Serializable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> MethodBeforeAdvice advice;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Create a new MethodBeforeAdviceInterceptor for the given advice.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> advice the MethodBeforeAdvice to wrap</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MethodBeforeAdviceInterceptor</span><span class="params">(MethodBeforeAdvice advice)</span> </span>&#123;</span><br><span class="line">      Assert.notNull(advice, <span class="string">&quot;Advice must not be null&quot;</span>);</span><br><span class="line">      <span class="keyword">this</span>.advice = advice;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(MethodInvocation mi)</span> <span class="keyword">throws</span> Throwable </span>&#123; <span class="comment">//invoke真正执行</span></span><br><span class="line">      <span class="keyword">this</span>.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());</span><br><span class="line">      <span class="keyword">return</span> mi.proceed();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>然后debug回到accept()方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012202236451.png" />





<h2 id="正式开始分析AOP运行流程-链式执行"><a href="#正式开始分析AOP运行流程-链式执行" class="headerlink" title="正式开始分析AOP运行流程-链式执行"></a>正式开始分析AOP运行流程-链式执行</h2><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012220057607.png"/>

<ol>
<li>F7进入方法，上面讲过会调用CglibAopProxy内部类的DynamicAdvisedInterceptor#intercept()。这次我们来说下为什么会跳到DynamicAdvisedInterceptor#intercept()方法</li>
<li>HelloService是一个代理对象，它的AOP代理是一个DynamicAdvisedInterceptor对象</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012220839278.png"/>

<ol start="3">
<li>而DynamicAdvisedInterceptor实现了MethodInterceptor接口</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicAdvisedInterceptor</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span>, <span class="title">Serializable</span></span>&#123;...&#125;</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>cglib代理就是，当你调用方法的时候，真正会调用到实现了MethodInterceptor接口的DynamicAdvisedInterceptor#intercept()</li>
<li><strong>至于具体的cglib原理，可以自己百度下</strong>。下面就看看intercept()的逻辑</li>
</ol>
<p>注意有两个MethodInterceptor，包名不一样</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> org.springframework.cglib.proxy;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">MethodInterceptor</span> <span class="keyword">extends</span> <span class="title">Callback</span> </span>&#123;</span><br><span class="line">    <span class="function">Object <span class="title">intercept</span><span class="params">(Object var1, Method var2, Object[] var3, MethodProxy var4)</span> <span class="keyword">throws</span> Throwable</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> org.aopalliance.intercept; <span class="comment">//Spring定义的AOP规范接口</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Nonnull;</span><br><span class="line"><span class="keyword">import</span> javax.annotation.Nullable;</span><br><span class="line"></span><br><span class="line"><span class="meta">@FunctionalInterface</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">MethodInterceptor</span> <span class="keyword">extends</span> <span class="title">Interceptor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function">Object <span class="title">invoke</span><span class="params">(<span class="meta">@Nonnull</span> MethodInvocation invocation)</span> <span class="keyword">throws</span> Throwable</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="DynamicAdvisedInterceptor-intercept"><a href="#DynamicAdvisedInterceptor-intercept" class="headerlink" title="DynamicAdvisedInterceptor#intercept()"></a>DynamicAdvisedInterceptor#intercept()</h3><p>有intercept的是cglib的MethodInterceptor接口</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Nullable</span> <span class="comment">//回调方法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object proxy, Method method, Object[] args, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   Object oldProxy = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">boolean</span> setProxyContext = <span class="keyword">false</span>;</span><br><span class="line">   Object target = <span class="keyword">null</span>;</span><br><span class="line">   <span class="comment">// 这里面有最原生的HelloService对象</span></span><br><span class="line">   TargetSource targetSource = <span class="keyword">this</span>.advised.getTargetSource();</span><br><span class="line">   <span class="keyword">try</span> &#123;  <span class="comment">//使用了代理对象就有增强功能</span></span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.advised.exposeProxy) &#123; <span class="comment">//使用ThreadLocal线程共享这个代理对象；</span></span><br><span class="line">         <span class="comment">// Make invocation available if necessary.</span></span><br><span class="line">         oldProxy = AopContext.setCurrentProxy(proxy);</span><br><span class="line">         setProxyContext = <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// Get as late as possible to minimize the time we &quot;own&quot; the target, in case it comes from a pool...</span></span><br><span class="line">      target = targetSource.getTarget();</span><br><span class="line">      Class&lt;?&gt; targetClass = (target != <span class="keyword">null</span> ? target.getClass() : <span class="keyword">null</span>);</span><br><span class="line">      List&lt;Object&gt; chain = <span class="keyword">this</span>.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);</span><br><span class="line">      Object retVal;  <span class="comment">//chain是AOP后置处理器在第一次的时候就生成好的5个增强器，然后封装成的MethodInterceptor</span></span><br><span class="line">      <span class="comment">// Check whether we only have one InvokerInterceptor: that is,</span></span><br><span class="line">      <span class="comment">// no real advice, but just reflective invocation of the target.</span></span><br><span class="line">      <span class="keyword">if</span> (chain.isEmpty() &amp;&amp; Modifier.isPublic(method.getModifiers())) &#123;</span><br><span class="line">         <span class="comment">// We can skip creating a MethodInvocation: just invoke the target directly.</span></span><br><span class="line">         <span class="comment">// Note that the final invoker must be an InvokerInterceptor, so we know</span></span><br><span class="line">         <span class="comment">// it does nothing but a reflective operation on the target, and no hot</span></span><br><span class="line">         <span class="comment">// swapping or fancy proxying.</span></span><br><span class="line">         Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);</span><br><span class="line">         retVal = methodProxy.invoke(target, argsToUse);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123; <span class="comment">//CglibMethodInvocation【FilterChain（维护索引）】，5个MethodInterceptor就是Filter</span></span><br><span class="line">         <span class="comment">//创建一个方法执行的东西(拦截器链在此执行) We need to create a method invocation...</span></span><br><span class="line">         retVal = <span class="keyword">new</span> CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();</span><br><span class="line">      &#125;</span><br><span class="line">      retVal = processReturnType(proxy, target, method, retVal);</span><br><span class="line">      <span class="keyword">return</span> retVal;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (target != <span class="keyword">null</span> &amp;&amp; !targetSource.isStatic()) &#123;</span><br><span class="line">         targetSource.releaseTarget(target);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (setProxyContext) &#123;</span><br><span class="line">         <span class="comment">// Restore old proxy.</span></span><br><span class="line">         AopContext.setCurrentProxy(oldProxy);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012223909994.png"  />

<p>在前面创建HelloService代理对象时创建好的方法拦截器，然后调用proceed()</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012224227624.png"  />

<h3 id="CglibMethodInvocation-proceed"><a href="#CglibMethodInvocation-proceed" class="headerlink" title="CglibMethodInvocation#proceed()"></a>CglibMethodInvocation#proceed()</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012224431389.png"  />



<p>顾名思义，就是用来执行Cglib生成的代理对象的方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012224629196.png"/>



<h4 id="CglibAopProxy-proceed"><a href="#CglibAopProxy-proceed" class="headerlink" title="CglibAopProxy#proceed()"></a>CglibAopProxy#proceed()</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012231748956.png"  />

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">proceed</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">super</span>.proceed(); <span class="comment">//调用父类的方法</span></span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (RuntimeException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> ex;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">      <span class="keyword">if</span> (ReflectionUtils.declaresException(getMethod(), ex.getClass()) ||</span><br><span class="line">            KotlinDetector.isKotlinType(getMethod().getDeclaringClass())) &#123;</span><br><span class="line">         <span class="comment">// Propagate original exception if declared on the target method</span></span><br><span class="line">         <span class="comment">// (with callers expecting it). Always propagate it for Kotlin code</span></span><br><span class="line">         <span class="comment">// since checked exceptions do not have to be explicitly declared there.</span></span><br><span class="line">         <span class="keyword">throw</span> ex;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// Checked exception thrown in the interceptor but not declared on the</span></span><br><span class="line">         <span class="comment">// target method signature -&gt; apply an UndeclaredThrowableException,</span></span><br><span class="line">         <span class="comment">// aligned with standard JDK dynamic proxy behavior.</span></span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> UndeclaredThrowableException(ex);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="ReflectiveMethodInvocation-proceed"><a href="#ReflectiveMethodInvocation-proceed" class="headerlink" title="ReflectiveMethodInvocation#proceed()"></a>ReflectiveMethodInvocation#proceed()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">proceed</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   <span class="comment">// 当前拦截器的索引有没有超过 拦截器总数量-1   We start with an index of -1 and increment early.</span></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.currentInterceptorIndex == <span class="keyword">this</span>.interceptorsAndDynamicMethodMatchers.size() - <span class="number">1</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> invokeJoinpoint();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   Object interceptorOrInterceptionAdvice =</span><br><span class="line">         <span class="keyword">this</span>.interceptorsAndDynamicMethodMatchers.get(++<span class="keyword">this</span>.currentInterceptorIndex);</span><br><span class="line">   <span class="keyword">if</span> (interceptorOrInterceptionAdvice <span class="keyword">instanceof</span> InterceptorAndDynamicMethodMatcher) &#123;</span><br><span class="line">      <span class="comment">// Evaluate dynamic method matcher here: static part will already have</span></span><br><span class="line">      <span class="comment">// been evaluated and found to match.</span></span><br><span class="line">      InterceptorAndDynamicMethodMatcher dm =</span><br><span class="line">            (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;</span><br><span class="line">      Class&lt;?&gt; targetClass = (<span class="keyword">this</span>.targetClass != <span class="keyword">null</span> ? <span class="keyword">this</span>.targetClass : <span class="keyword">this</span>.method.getDeclaringClass());</span><br><span class="line">      <span class="keyword">if</span> (dm.methodMatcher.matches(<span class="keyword">this</span>.method, targetClass, <span class="keyword">this</span>.arguments)) &#123;</span><br><span class="line">         <span class="keyword">return</span> dm.interceptor.invoke(<span class="keyword">this</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// Dynamic matching failed.</span></span><br><span class="line">         <span class="comment">// Skip this interceptor and invoke the next in the chain.</span></span><br><span class="line">         <span class="keyword">return</span> proceed();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// It&#x27;s an interceptor, so we just invoke it: The pointcut will have</span></span><br><span class="line">      <span class="comment">// been evaluated statically before this object was constructed.</span></span><br><span class="line">      <span class="keyword">return</span> ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(<span class="keyword">this</span>);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012225055742.png"/>

<p>上面5个拦截器都继承了Spring的org.aopalliance.intercept.MethodInterceptor，和Cglib的MethodInterceptor没关系了</p>
<h4 id="ExposeInvocationInterceptor第一个拦截器"><a href="#ExposeInvocationInterceptor第一个拦截器" class="headerlink" title="ExposeInvocationInterceptor第一个拦截器"></a>ExposeInvocationInterceptor第一个拦截器</h4><p>获取第一个拦截器ExposeInvocationInterceptor</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012225804099.png"/>

<p>往下走，直接走到了这里，准备调用ExposeInvocationInterceptor的invoke()</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012230419970.png"  />



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012230646766.png"/>

<h5 id="CglibAopProxy-proceed-1"><a href="#CglibAopProxy-proceed-1" class="headerlink" title="CglibAopProxy#proceed()"></a>CglibAopProxy#proceed()</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012230842658.png"  />

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">proceed</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">super</span>.proceed(); <span class="comment">//调用父类的方法</span></span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (RuntimeException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> ex;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">      <span class="keyword">if</span> (ReflectionUtils.declaresException(getMethod(), ex.getClass()) ||</span><br><span class="line">            KotlinDetector.isKotlinType(getMethod().getDeclaringClass())) &#123;</span><br><span class="line">         <span class="comment">// Propagate original exception if declared on the target method</span></span><br><span class="line">         <span class="comment">// (with callers expecting it). Always propagate it for Kotlin code</span></span><br><span class="line">         <span class="comment">// since checked exceptions do not have to be explicitly declared there.</span></span><br><span class="line">         <span class="keyword">throw</span> ex;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// Checked exception thrown in the interceptor but not declared on the</span></span><br><span class="line">         <span class="comment">// target method signature -&gt; apply an UndeclaredThrowableException,</span></span><br><span class="line">         <span class="comment">// aligned with standard JDK dynamic proxy behavior.</span></span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> UndeclaredThrowableException(ex);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>结果又调回了，很明显这是个递归调用</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012230930440.png" />

<h4 id="MethodBeforeAdviceInterceptor-前置通知"><a href="#MethodBeforeAdviceInterceptor-前置通知" class="headerlink" title="MethodBeforeAdviceInterceptor-前置通知"></a>MethodBeforeAdviceInterceptor-前置通知</h4><p>然后后面的调用逻辑和前面就一样了，如下</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012231135459.png"  />



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012231202337.png" />



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012231327882.png"/>

<p>这个时候就先执行切面的before方法，前置通知就执行了</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012232119227.png" />

<p>继续调父类的方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012231412866.png"/>



<h4 id="AspectJAfterAdvice-后置通知"><a href="#AspectJAfterAdvice-后置通知" class="headerlink" title="AspectJAfterAdvice-后置通知"></a>AspectJAfterAdvice-后置通知</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012232315412.png"  />

<p>后置通知这里先不执行，先继续执行下面的方法拦截器链路，最后finally再执行后置通知</p>
<h4 id="AfterReturningAdviceInterceptor-返回通知"><a href="#AfterReturningAdviceInterceptor-返回通知" class="headerlink" title="AfterReturningAdviceInterceptor-返回通知"></a>AfterReturningAdviceInterceptor-返回通知</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012232551952.png"  />

<ol>
<li>先往下走，我们就继续</li>
</ol>
<h4 id="AspectJAfterThrowingAdvice-异常通知"><a href="#AspectJAfterThrowingAdvice-异常通知" class="headerlink" title="AspectJAfterThrowingAdvice-异常通知"></a>AspectJAfterThrowingAdvice-异常通知</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012232910377.png"/>

<p>继续往下发现索引要超了</p>
<h4 id="真正执行sayhello"><a href="#真正执行sayhello" class="headerlink" title="真正执行sayhello()"></a>真正执行sayhello()</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233113154.png"/>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233212466.png"  />



<p>放行之后看控制台，sayhello方法就打印了。并且到目前为止，只有前面说的前置通知执行了。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233317479.png"  />

<p>然后咱们就往后返，</p>
<h4 id="—返回—"><a href="#—返回—" class="headerlink" title="—返回—"></a>—返回—</h4><h4 id="AspectJAfterThrowingAdvice-异常通知-1"><a href="#AspectJAfterThrowingAdvice-异常通知-1" class="headerlink" title="AspectJAfterThrowingAdvice-异常通知"></a>AspectJAfterThrowingAdvice-异常通知</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233506053.png"  />

<p>咱们这里没异常，就继续返回了</p>
<h4 id="AfterReturningAdviceInterceptor-返回通知-1"><a href="#AfterReturningAdviceInterceptor-返回通知-1" class="headerlink" title="AfterReturningAdviceInterceptor-返回通知"></a>AfterReturningAdviceInterceptor-返回通知</h4><p>返回到这里，准备执行返回通知</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233633239.png" />



<p>放行之后的控制台</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233731212.png" />

<p>继续返回</p>
<h4 id="AspectJAfterAdvice-后置通知-1"><a href="#AspectJAfterAdvice-后置通知-1" class="headerlink" title="AspectJAfterAdvice-后置通知"></a>AspectJAfterAdvice-后置通知</h4><p>准备执行后置通知</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233837744.png">

<p>放行finally之后的控制台</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012233944290.png"  />







<h4 id="ExposeInvocationInterceptor"><a href="#ExposeInvocationInterceptor" class="headerlink" title="ExposeInvocationInterceptor"></a>ExposeInvocationInterceptor</h4><p>继续返回</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012234108557.png" />



<h4 id="CglibAopProxy-DynamicAdvisedInterceptor"><a href="#CglibAopProxy-DynamicAdvisedInterceptor" class="headerlink" title="CglibAopProxy$DynamicAdvisedInterceptor"></a>CglibAopProxy$DynamicAdvisedInterceptor</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211012234214735.png"  />



<p>最后over，回到刚开头说的那个地方</p>
<h1 id="Spring杂项"><a href="#Spring杂项" class="headerlink" title="Spring杂项"></a>Spring杂项</h1><h2 id="监听器原理【事件原理】"><a href="#监听器原理【事件原理】" class="headerlink" title="监听器原理【事件原理】"></a>监听器原理【事件原理】</h2><h3 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h3><h4 id="AppEventListener"><a href="#AppEventListener" class="headerlink" title="AppEventListener"></a>AppEventListener</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppEventListener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">AppEventListener</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;AppEventListener...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@EventListener(MessageEvent.class)</span> <span class="comment">//监听事件</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listenMessage</span><span class="params">(MessageEvent event)</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;Message事件到达...&quot;</span>+event+<span class="string">&quot;；已发送邮件....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="meta">@EventListener(ChangeEvent.class)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listenChange</span><span class="params">(ChangeEvent event)</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;Change事件到达...&quot;</span>+event+<span class="string">&quot;；已同步状态....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@EventListener(PayloadApplicationEvent.class)</span> <span class="comment">//感知任意对象事件的</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listenPayload</span><span class="params">(PayloadApplicationEvent&lt;A&gt; event)</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;Payload事件到达...&quot;</span>+event.getPayload()+<span class="string">&quot;；已进行处理....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="AppEventPublisher"><a href="#AppEventPublisher" class="headerlink" title="AppEventPublisher"></a>AppEventPublisher</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppEventPublisher</span> <span class="keyword">implements</span> <span class="title">ApplicationEventPublisherAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   ApplicationEventPublisher eventPublisher;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">AppEventPublisher</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;AppEventPublisher....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationEventPublisher</span><span class="params">(ApplicationEventPublisher applicationEventPublisher)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.eventPublisher = applicationEventPublisher;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">publish</span><span class="params">(ApplicationEvent applicationEvent)</span></span>&#123;</span><br><span class="line">      eventPublisher.publishEvent(applicationEvent);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">publish</span><span class="params">(Object o)</span></span>&#123;</span><br><span class="line">      eventPublisher.publishEvent(o);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="ChangeEvent"><a href="#ChangeEvent" class="headerlink" title="ChangeEvent"></a>ChangeEvent</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 事件需要实现序列化接口</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ChangeEvent</span> <span class="keyword">extends</span> <span class="title">ApplicationEvent</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">0L</span>;</span><br><span class="line">   <span class="keyword">private</span> String state;</span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="title">ChangeEvent</span><span class="params">(Object source)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">super</span>(source);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">ChangeEvent</span><span class="params">(Object source,String state)</span></span>&#123;</span><br><span class="line">      <span class="keyword">super</span>(source);</span><br><span class="line">      <span class="keyword">this</span>.state = state;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getState</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> state;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;ChangeEvent&#123;&quot;</span> +</span><br><span class="line">            <span class="string">&quot;state=&#x27;&quot;</span> + state + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">            <span class="string">&quot;, source=&quot;</span> + source +</span><br><span class="line">            <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="MessageEvent"><a href="#MessageEvent" class="headerlink" title="MessageEvent"></a>MessageEvent</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 事件需要实现序列化接口</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MessageEvent</span> <span class="keyword">extends</span> <span class="title">ApplicationEvent</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">0L</span>;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MessageEvent</span><span class="params">(String source)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">super</span>(source);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;MessageEvent&#123;&quot;</span> +</span><br><span class="line">            <span class="string">&quot;, source=&quot;</span> + source +</span><br><span class="line">            <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="AnnotationMainTest"><a href="#AnnotationMainTest" class="headerlink" title="AnnotationMainTest"></a>AnnotationMainTest</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.imlql.spring;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 注解版Spring的用法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AnnotationMainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      ApplicationContext applicationContext =</span><br><span class="line">            <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfig.class);</span><br><span class="line">      </span><br><span class="line">       </span><br><span class="line">	  <span class="comment">// 下面两种使用方法都可以</span></span><br><span class="line"><span class="comment">//    applicationContext.publishEvent(new Object());</span></span><br><span class="line"><span class="comment">//    applicationContext.publishEvent(new ApplicationEvent() &#123;</span></span><br><span class="line"><span class="comment">//       @Override</span></span><br><span class="line"><span class="comment">//       public String toString() &#123;</span></span><br><span class="line"><span class="comment">//          return super.toString();</span></span><br><span class="line"><span class="comment">//       &#125;</span></span><br><span class="line"><span class="comment">//    &#125;);</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">//测试事件</span></span><br><span class="line">      AppEventPublisher eventPublisher = applicationContext.getBean(AppEventPublisher.class);</span><br><span class="line">      eventPublisher.publish(<span class="keyword">new</span> A());</span><br><span class="line">      eventPublisher.publish(<span class="keyword">new</span> MessageEvent(<span class="string">&quot;hello，你好&quot;</span>));</span><br><span class="line">      eventPublisher.publish(<span class="keyword">new</span> ChangeEvent(eventPublisher,<span class="string">&quot;sending...&quot;</span>));</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>在还未进行refresh()十二大步刷新时，容器就已经有了这两事件相关的Bean定义信息了。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013162535782.png"/>



<h3 id="EventListenerMethodProcessor"><a href="#EventListenerMethodProcessor" class="headerlink" title="EventListenerMethodProcessor"></a>EventListenerMethodProcessor</h3><h4 id="继承树"><a href="#继承树" class="headerlink" title="继承树"></a>继承树</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013162805867.png"  />

<ol>
<li>我们看到实现了SmartInitializingSingleton和BeanFactoryPostProcessor</li>
<li>BeanFactoryPostProcessor我们反复在说，就是工厂后置处理环节。EventListenerMethodProcessor实现了BeanFactoryPostProcessor，说明他在工厂后置处理环节会做事</li>
<li>SmartInitializingSingleton我们虽然说的不多，但也说过几次，调用链路如下。说明它会在容器刷新12大步的最后一步做事，并且看代码位置是在所有Bean创建完成之后做事。</li>
</ol>
<blockquote>
<p>AbstractApplicationContext#refresh()  ==&gt;   AbstractApplicationContext#finishBeanFactoryInitialization()  ==&gt;  DefaultListableBeanFactory#preInstantiateSingletons()</p>
</blockquote>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013164017769.png" />



<p>怎么分析呢？还是老办法，给EventListenerMethodProcessor标注@Override的方法打上断点</p>
<p>Debug启动</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013170249700.png"/>

<p>果然是从工厂后置处理那里过来的</p>
<p>放行，继续往下走。果然SmartInitializingSingleton这里开始做事了</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013170435169.png" />



<h4 id="EventListenerMethodProcessor-afterSingletonsInstantiated"><a href="#EventListenerMethodProcessor-afterSingletonsInstantiated" class="headerlink" title="EventListenerMethodProcessor#afterSingletonsInstantiated()"></a>EventListenerMethodProcessor#afterSingletonsInstantiated()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterSingletonsInstantiated</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   ConfigurableListableBeanFactory beanFactory = <span class="keyword">this</span>.beanFactory;</span><br><span class="line">   Assert.state(<span class="keyword">this</span>.beanFactory != <span class="keyword">null</span>, <span class="string">&quot;No ConfigurableListableBeanFactory set&quot;</span>);</span><br><span class="line">   String[] beanNames = beanFactory.getBeanNamesForType(Object.class);</span><br><span class="line">   <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">      <span class="keyword">if</span> (!ScopedProxyUtils.isScopedTarget(beanName)) &#123;</span><br><span class="line">         Class&lt;?&gt; type = <span class="keyword">null</span>;</span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">            type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">            <span class="comment">// An unresolvable bean type, probably from a lazy bean - let&#x27;s ignore it.</span></span><br><span class="line">            <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">               logger.debug(<span class="string">&quot;Could not resolve target class for bean with name &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>, ex);</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">if</span> (type != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (ScopedObject.class.isAssignableFrom(type)) &#123;</span><br><span class="line">               <span class="keyword">try</span> &#123;</span><br><span class="line">                  Class&lt;?&gt; targetClass = AutoProxyUtils.determineTargetClass(</span><br><span class="line">                        beanFactory, ScopedProxyUtils.getTargetBeanName(beanName));</span><br><span class="line">                  <span class="keyword">if</span> (targetClass != <span class="keyword">null</span>) &#123;</span><br><span class="line">                     type = targetClass;</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">                  <span class="comment">// An invalid scoped proxy arrangement - let&#x27;s ignore it.</span></span><br><span class="line">                  <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                     logger.debug(<span class="string">&quot;Could not resolve target bean for scoped proxy &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>, ex);</span><br><span class="line">                  &#125;</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">               processBean(beanName, type); <span class="comment">//主要是这里</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">               <span class="keyword">throw</span> <span class="keyword">new</span> BeanInitializationException(<span class="string">&quot;Failed to process @EventListener &quot;</span> +</span><br><span class="line">                     <span class="string">&quot;annotation on bean with name &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>, ex);</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>我们在这里打上条件断点</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013170852409.png"/>







<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013171247356.png" />

<p>F7进入下面的方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013171641031.png"  />

<p>咱们发现是创建了一个适配器</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013171728867.png"  />

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ApplicationListenerMethodAdapter</span><span class="params">(String beanName, Class&lt;?&gt; targetClass, Method method)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">this</span>.beanName = beanName;</span><br><span class="line">   <span class="keyword">this</span>.method = BridgeMethodResolver.findBridgedMethod(method);</span><br><span class="line">   <span class="keyword">this</span>.targetMethod = (!Proxy.isProxyClass(targetClass) ?</span><br><span class="line">         AopUtils.getMostSpecificMethod(method, targetClass) : <span class="keyword">this</span>.method);</span><br><span class="line">   <span class="keyword">this</span>.methodKey = <span class="keyword">new</span> AnnotatedElementKey(<span class="keyword">this</span>.targetMethod, targetClass);</span><br><span class="line"></span><br><span class="line">   EventListener ann = AnnotatedElementUtils.findMergedAnnotation(<span class="keyword">this</span>.targetMethod, EventListener.class);</span><br><span class="line">   <span class="keyword">this</span>.declaredEventTypes = resolveDeclaredEventTypes(method, ann);</span><br><span class="line">   <span class="keyword">this</span>.condition = (ann != <span class="keyword">null</span> ? ann.condition() : <span class="keyword">null</span>);</span><br><span class="line">   <span class="keyword">this</span>.order = resolveOrder(<span class="keyword">this</span>.targetMethod);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为啥要创建这样一个适配器呢？虽然我们的AppEventListener不是监听器，它只是在方法里标注了监听注解，我们自己没有写监听器。但是咱们解析@EventListener注解之后，在这里生成的适配器却实现了EventListener，也就说明这个适配器就是个监听器。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013171936784.png"  />



<p>继续往下放行</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013172130892.png"  />



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013172239216.png"  />

<p>把适配器放到了事件多播器里</p>
<ol>
<li>这个思想就是，咱们自己创建的AppEventListener不是监听器，只在方法里标了注解</li>
<li>spring准备了另外一个类ApplicationListenerMethodAdapter，把你这个beanName和方法名等等信息封装到这里。然后放到事件多播器里</li>
<li>等以后真正的事件来了之后派发给ApplicationListenerMethodAdapter，ApplicationListenerMethodAdapter再用之前保存的信息反射调用实际的方法</li>
</ol>
<p>最后就是三个方法，三个适配器</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013172925798.png"  />



<h4 id="监听器如何感知到事件？"><a href="#监听器如何感知到事件？" class="headerlink" title="监听器如何感知到事件？"></a>监听器如何感知到事件？</h4><p>给下面的位置打上断点</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013173037562.png"  />



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_07/image-20211013173146059.png" />

<h5 id="AbstractApplicationContext-publishEvent"><a href="#AbstractApplicationContext-publishEvent" class="headerlink" title="AbstractApplicationContext#publishEvent()"></a>AbstractApplicationContext#publishEvent()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">publishEvent</span><span class="params">(Object event)</span> </span>&#123;</span><br><span class="line">   publishEvent(event, <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">publishEvent</span><span class="params">(Object event, <span class="meta">@Nullable</span> ResolvableType eventType)</span> </span>&#123;</span><br><span class="line">   Assert.notNull(event, <span class="string">&quot;Event must not be null&quot;</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Decorate event as an ApplicationEvent if necessary</span></span><br><span class="line">   ApplicationEvent applicationEvent;</span><br><span class="line">   <span class="keyword">if</span> (event <span class="keyword">instanceof</span> ApplicationEvent) &#123; <span class="comment">// ApplicationEvent接口下的事件</span></span><br><span class="line">      applicationEvent = (ApplicationEvent) event;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;  <span class="comment">//任意对象作为事件最终被封装到了 PayloadApplicationEvent</span></span><br><span class="line">      applicationEvent = <span class="keyword">new</span> PayloadApplicationEvent&lt;&gt;(<span class="keyword">this</span>, event);</span><br><span class="line">      <span class="keyword">if</span> (eventType == <span class="keyword">null</span>) &#123;</span><br><span class="line">         eventType = ((PayloadApplicationEvent&lt;?&gt;) applicationEvent).getResolvableType();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Multicast right now if possible - or lazily once the multicaster is initialized</span></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.earlyApplicationEvents != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">this</span>.earlyApplicationEvents.add(applicationEvent);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123; <span class="comment">//拿到多播器发送事件即可</span></span><br><span class="line">      getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Publish event via parent context as well...</span></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.parent != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.parent <span class="keyword">instanceof</span> AbstractApplicationContext) &#123;</span><br><span class="line">         ((AbstractApplicationContext) <span class="keyword">this</span>.parent).publishEvent(event, eventType);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="keyword">this</span>.parent.publishEvent(event);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="SimpleApplicationEventMulticaster-multicastEvent"><a href="#SimpleApplicationEventMulticaster-multicastEvent" class="headerlink" title="SimpleApplicationEventMulticaster#multicastEvent()"></a>SimpleApplicationEventMulticaster#multicastEvent()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="comment">//事件派发可以是异步</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">multicastEvent</span><span class="params">(<span class="keyword">final</span> ApplicationEvent event, <span class="meta">@Nullable</span> ResolvableType eventType)</span> </span>&#123;</span><br><span class="line">      ResolvableType type = (eventType != <span class="keyword">null</span> ? eventType : resolveDefaultEventType(event));</span><br><span class="line">      Executor executor = getTaskExecutor();</span><br><span class="line">      <span class="keyword">for</span> (ApplicationListener&lt;?&gt; listener : getApplicationListeners(event, type)) &#123;</span><br><span class="line">         <span class="keyword">if</span> (executor != <span class="keyword">null</span>) &#123;  <span class="comment">//使用观察者模式，把所有事件监听器拿来，调用他们的onApplicationEvent方法即可</span></span><br><span class="line">            executor.execute(() -&gt; invokeListener(listener, event));</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">else</span> &#123;</span><br><span class="line">            invokeListener(listener, event);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">invokeListener</span><span class="params">(ApplicationListener&lt;?&gt; listener, ApplicationEvent event)</span> </span>&#123;</span><br><span class="line">	ErrorHandler errorHandler = getErrorHandler();</span><br><span class="line">	<span class="keyword">if</span> (errorHandler != <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			doInvokeListener(listener, event);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (Throwable err) &#123;</span><br><span class="line">			errorHandler.handleError(err);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		doInvokeListener(listener, event);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SuppressWarnings(&#123;&quot;rawtypes&quot;, &quot;unchecked&quot;&#125;)</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doInvokeListener</span><span class="params">(ApplicationListener listener, ApplicationEvent event)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		listener.onApplicationEvent(event);<span class="comment">//调用咱们实现的方法</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (ClassCastException ex) &#123;</span><br><span class="line">		String msg = ex.getMessage();</span><br><span class="line">		<span class="keyword">if</span> (msg == <span class="keyword">null</span> || matchesClassCastMessage(msg, event.getClass()) ||</span><br><span class="line">				(event <span class="keyword">instanceof</span> PayloadApplicationEvent &amp;&amp;</span><br><span class="line">						matchesClassCastMessage(msg, ((PayloadApplicationEvent) event).getPayload().getClass()))) &#123;</span><br><span class="line">			<span class="comment">// Possibly a lambda-defined listener which we could not resolve the generic event type for</span></span><br><span class="line">			<span class="comment">// -&gt; let&#x27;s suppress the exception.</span></span><br><span class="line">			Log loggerToUse = <span class="keyword">this</span>.lazyLogger;</span><br><span class="line">			<span class="keyword">if</span> (loggerToUse == <span class="keyword">null</span>) &#123;</span><br><span class="line">				loggerToUse = LogFactory.getLog(getClass());</span><br><span class="line">				<span class="keyword">this</span>.lazyLogger = loggerToUse;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (loggerToUse.isTraceEnabled()) &#123;</span><br><span class="line">				loggerToUse.trace(<span class="string">&quot;Non-matching event type for listener: &quot;</span> + listener, ex);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">throw</span> ex;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>













































</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/fb3552e0.html">https://imlql.cn/post/fb3552e0.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring%E6%BA%90%E7%A0%81/">Spring源码</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/c8dd1418.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div class="next-post pull-right"><a href="/post/598f6b0d.html"><img class="next-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring源码系列-第6章-AOP的后置处理器和代理对象的创建</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/41fb8d9e.html" title="Spring源码系列-第2章-后置工厂处理器和Bean生命周期"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-21</div><div class="title">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div><div><a href="/post/49f419ae.html" title="Spring源码系列-第4章-Bean初始化流程"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-27</div><div class="title">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div><a href="/post/c8dd1418.html" title="Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-20</div><div class="title">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div><a href="/post/6f2cef28.html" title="Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-21</div><div class="title">Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理</div></div></a></div><div><a href="/post/4dfb096b.html" title="Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理</div></div></a></div><div><a href="/post/e3da4d66.html" title="Spring源码系列-第12章-SpringBoot源码-自动配置原理和内嵌Tomcat启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-06</div><div class="title">Spring源码系列-第12章-SpringBoot源码-自动配置原理和内嵌Tomcat启动原理</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC7%E7%AB%A0-AOP%E7%9A%84%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%8E%9F%E7%90%86%E5%92%8C%E7%9B%91%E5%90%AC%E5%99%A8%E5%8E%9F%E7%90%86"><span class="toc-text">第7章-AOP的执行流程原理和监听器原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E5%9B%BE-AOP%E8%BF%90%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%8E%9F%E7%90%86"><span class="toc-text">流程图-AOP运行流程原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%B1Aop%E7%9A%84%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%BC%95%E5%87%BA%E6%96%B9%E6%B3%95%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-text">由Aop的执行流程引出方法拦截器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%AE%8C%E4%BB%A3%E7%90%86%E5%AF%B9%E8%B1%A1%E4%B9%8B%E5%90%8E%EF%BC%8C%E6%80%8E%E4%B9%88%E6%89%A7%E8%A1%8C%E7%9A%84%E5%91%A2%EF%BC%9F"><span class="toc-text">创建完代理对象之后，怎么执行的呢？</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#CglibAopProxy-intercept"><span class="toc-text">CglibAopProxy#intercept()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CglibAopProxy-getInterceptorsAndDynamicInterceptionAdvice"><span class="toc-text">CglibAopProxy#getInterceptorsAndDynamicInterceptionAdvice()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E7%94%9F%E6%88%90%E7%9A%84%E6%96%B9%E6%B3%95%E6%8B%A6%E6%88%AA%E5%99%A8%EF%BC%9F"><span class="toc-text">如何生成的方法拦截器？</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DefaultAdvisorChainFactory-getInterceptorsAndDynamicInterceptionAdvice-%E5%BC%80%E5%A7%8B%E5%B0%86%E5%A2%9E%E5%BC%BA%E5%99%A8%E8%BD%AC%E4%B8%BA%E6%96%B9%E6%B3%95%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-text">DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice()开始将增强器转为方法拦截器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DefaultAdvisorAdapterRegistry-getInterceptors"><span class="toc-text">DefaultAdvisorAdapterRegistry#getInterceptors()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#MethodBeforeAdviceAdapter%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F%E5%B0%86%E5%A2%9E%E5%BC%BA%E5%99%A8%E9%80%82%E9%85%8D%E6%88%90%E6%96%B9%E6%B3%95%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-text">MethodBeforeAdviceAdapter适配器模式将增强器适配成方法拦截器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#MethodBeforeAdviceInterceptor"><span class="toc-text">MethodBeforeAdviceInterceptor</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%A3%E5%BC%8F%E5%BC%80%E5%A7%8B%E5%88%86%E6%9E%90AOP%E8%BF%90%E8%A1%8C%E6%B5%81%E7%A8%8B-%E9%93%BE%E5%BC%8F%E6%89%A7%E8%A1%8C"><span class="toc-text">正式开始分析AOP运行流程-链式执行</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#DynamicAdvisedInterceptor-intercept"><span class="toc-text">DynamicAdvisedInterceptor#intercept()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#CglibMethodInvocation-proceed"><span class="toc-text">CglibMethodInvocation#proceed()</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#CglibAopProxy-proceed"><span class="toc-text">CglibAopProxy#proceed()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ReflectiveMethodInvocation-proceed"><span class="toc-text">ReflectiveMethodInvocation#proceed()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ExposeInvocationInterceptor%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-text">ExposeInvocationInterceptor第一个拦截器</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#CglibAopProxy-proceed-1"><span class="toc-text">CglibAopProxy#proceed()</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#MethodBeforeAdviceInterceptor-%E5%89%8D%E7%BD%AE%E9%80%9A%E7%9F%A5"><span class="toc-text">MethodBeforeAdviceInterceptor-前置通知</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AspectJAfterAdvice-%E5%90%8E%E7%BD%AE%E9%80%9A%E7%9F%A5"><span class="toc-text">AspectJAfterAdvice-后置通知</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AfterReturningAdviceInterceptor-%E8%BF%94%E5%9B%9E%E9%80%9A%E7%9F%A5"><span class="toc-text">AfterReturningAdviceInterceptor-返回通知</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AspectJAfterThrowingAdvice-%E5%BC%82%E5%B8%B8%E9%80%9A%E7%9F%A5"><span class="toc-text">AspectJAfterThrowingAdvice-异常通知</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9C%9F%E6%AD%A3%E6%89%A7%E8%A1%8Csayhello"><span class="toc-text">真正执行sayhello()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E2%80%94%E8%BF%94%E5%9B%9E%E2%80%94"><span class="toc-text">—返回—</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AspectJAfterThrowingAdvice-%E5%BC%82%E5%B8%B8%E9%80%9A%E7%9F%A5-1"><span class="toc-text">AspectJAfterThrowingAdvice-异常通知</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AfterReturningAdviceInterceptor-%E8%BF%94%E5%9B%9E%E9%80%9A%E7%9F%A5-1"><span class="toc-text">AfterReturningAdviceInterceptor-返回通知</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AspectJAfterAdvice-%E5%90%8E%E7%BD%AE%E9%80%9A%E7%9F%A5-1"><span class="toc-text">AspectJAfterAdvice-后置通知</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ExposeInvocationInterceptor"><span class="toc-text">ExposeInvocationInterceptor</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CglibAopProxy-DynamicAdvisedInterceptor"><span class="toc-text">CglibAopProxy$DynamicAdvisedInterceptor</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Spring%E6%9D%82%E9%A1%B9"><span class="toc-text">Spring杂项</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%9B%91%E5%90%AC%E5%99%A8%E5%8E%9F%E7%90%86%E3%80%90%E4%BA%8B%E4%BB%B6%E5%8E%9F%E7%90%86%E3%80%91"><span class="toc-text">监听器原理【事件原理】</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-text">测试类</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#AppEventListener"><span class="toc-text">AppEventListener</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AppEventPublisher"><span class="toc-text">AppEventPublisher</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ChangeEvent"><span class="toc-text">ChangeEvent</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#MessageEvent"><span class="toc-text">MessageEvent</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AnnotationMainTest"><span class="toc-text">AnnotationMainTest</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#EventListenerMethodProcessor"><span class="toc-text">EventListenerMethodProcessor</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E6%A0%91"><span class="toc-text">继承树</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#EventListenerMethodProcessor-afterSingletonsInstantiated"><span class="toc-text">EventListenerMethodProcessor#afterSingletonsInstantiated()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%91%E5%90%AC%E5%99%A8%E5%A6%82%E4%BD%95%E6%84%9F%E7%9F%A5%E5%88%B0%E4%BA%8B%E4%BB%B6%EF%BC%9F"><span class="toc-text">监听器如何感知到事件？</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractApplicationContext-publishEvent"><span class="toc-text">AbstractApplicationContext#publishEvent()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#SimpleApplicationEventMulticaster-multicastEvent"><span class="toc-text">SimpleApplicationEventMulticaster#multicastEvent()</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>